<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #121212;
            color: #00ffcc;
            font-family: 'Courier New', monospace;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
        }

        .game-container {
            display: flex;
            gap: 20px;
            align-items: flex-start;
        }

        .game-board {
            position: relative;
            border: 2px solid #00ffcc;
            box-shadow: 0 0 10px #00ffcc;
        }

        #gameCanvas {
            background-color: #1e1e1e;
        }

        .control-panel {
            display: flex;
            flex-direction: column;
            gap: 15px;
            padding: 15px;
            border: 1px solid #00ffcc;
            border-radius: 5px;
            box-shadow: 0 0 5px #00ffcc;
            background-color: rgba(30, 30, 30, 0.8);
        }

        .score-board {
            text-align: center;
            font-size: 18px;
            margin-bottom: 10px;
        }

        .controls {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        button {
            background-color: #1e1e1e;
            color: #00ffcc;
            border: 1px solid #00ffcc;
            border-radius: 3px;
            padding: 8px 12px;
            cursor: pointer;
            font-family: 'Courier New', monospace;
            transition: all 0.3s;
        }

        button:hover {
            background-color: #00ffcc;
            color: #121212;
            box-shadow: 0 0 5px #00ffcc;
        }

        .slider-container {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .mode-toggle {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .footer {
            margin-top: 20px;
            font-size: 14px;
            color: rgba(0, 255, 204, 0.7);
        }

        h1 {
            text-shadow: 0 0 10px #00ffcc;
            letter-spacing: 2px;
        }
    </style>
</head>
<body>
    <h1>贪吃蛇游戏</h1>
    
    <div class="game-container">
        <canvas id="gameCanvas" width="400" height="400"></canvas>
        
        <div class="control-panel">
            <div class="score-board">
                <div>得分: <span id="score">0</span></div>
                <div>最高分: <span id="highScore">0</span></div>
                <div>速度: <span id="speed">1</span></div>
            </div>
            
            <div class="controls">
                <button id="startBtn">开始游戏</button>
                <button id="pauseBtn">暂停/继续</button>
                <button id="restartBtn">重新开始</button>
                
                <div class="slider-container">
                    <label for="speedSlider">速度控制:</label>
                    <input type="range" id="speedSlider" min="1" max="10" value="1">
                </div>
                
                <div class="mode-toggle">
                    <label>游戏模式:</label>
                    <button id="manualModeBtn">手动模式</button>
                    <button id="autoModeBtn">自动模式</button>
                </div>
            </div>
        </div>
    </div>
    
    <div class="footer">
        <p>Powered by Qwen</p>
    </div>

    <script>
        // 游戏变量
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const highScoreElement = document.getElementById('highScore');
        const speedElement = document.getElementById('speed');
        const speedSlider = document.getElementById('speedSlider');
        const startBtn = document.getElementById('startBtn');
        const pauseBtn = document.getElementById('pauseBtn');
        const restartBtn = document.getElementById('restartBtn');
        const manualModeBtn = document.getElementById('manualModeBtn');
        const autoModeBtn = document.getElementById('autoModeBtn');

        // 游戏设置
        const gridSize = 20;
        const tileCount = canvas.width / gridSize;
        
        // 游戏状态
        let snake = [];
        let food = {};
        let dx = 0;
        let dy = 0;
        let score = 0;
        let highScore = localStorage.getItem('snakeHighScore') || 0;
        let gameSpeed = 1;
        let gameRunning = false;
        let gamePaused = false;
        let gameLoopInterval;
        let gameMode = 'manual'; // 'manual' or 'auto'
        let particles = []; // 粒子效果数组

        // 初始化游戏
        function initGame() {
            // 初始化蛇
            snake = [
                {x: 10, y: 10}, // 蛇头
                {x: 9, y: 10},
                {x: 8, y: 10}
            ];
            
            // 初始化食物
            placeFood();
            
            // 初始化方向
            dx = 1;
            dy = 0;
            
            // 重置分数
            score = 0;
            scoreElement.textContent = score;
            highScoreElement.textContent = highScore;
            speedElement.textContent = gameSpeed;
            
            // 绘制初始状态
            draw();
        }

        // 放置食物
        function placeFood() {
            let newFood;
            let foodOnSnake;
            
            do {
                foodOnSnake = false;
                newFood = {
                    x: Math.floor(Math.random() * tileCount),
                    y: Math.floor(Math.random() * tileCount)
                };
                
                // 确保食物不在蛇身上
                for (let segment of snake) {
                    if (segment.x === newFood.x && segment.y === newFood.y) {
                        foodOnSnake = true;
                        break;
                    }
                }
            } while (foodOnSnake);
            
            food = newFood;
        }
        
        // 创建粒子效果
        function createParticles(x, y, color, count) {
            for (let i = 0; i < count; i++) {
                particles.push({
                    x: x * gridSize + gridSize / 2,
                    y: y * gridSize + gridSize / 2,
                    dx: (Math.random() - 0.5) * 4,
                    dy: (Math.random() - 0.5) * 4,
                    radius: Math.random() * 3 + 1,
                    color: color,
                    life: 30 // 粒子生命周期
                });
            }
        }
        
        // 更新粒子效果
        function updateParticles() {
            for (let i = particles.length - 1; i >= 0; i--) {
                let p = particles[i];
                p.x += p.dx;
                p.y += p.dy;
                p.life--;
                
                if (p.life <= 0) {
                    particles.splice(i, 1);
                }
            }
        }
        
        // 绘制粒子效果
        function drawParticles() {
            for (let i = 0; i < particles.length; i++) {
                let p = particles[i];
                ctx.fillStyle = p.color;
                ctx.globalAlpha = p.life / 30; // 根据生命周期调整透明度
                ctx.beginPath();
                ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2);
                ctx.fill();
            }
            ctx.globalAlpha = 1; // 重置透明度
        }

        // 绘制游戏
        function draw() {
            // 清空画布
            ctx.fillStyle = '#1e1e1e';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 绘制网格
            ctx.strokeStyle = '#2a2a2a';
            for (let i = 0; i < tileCount; i++) {
                for (let j = 0; j < tileCount; j++) {
                    ctx.strokeRect(i * gridSize, j * gridSize, gridSize, gridSize);
                }
            }
            
            // 更新和绘制粒子效果
            updateParticles();
            drawParticles();
            
            // 绘制蛇
            snake.forEach((segment, index) => {
                if (index === 0) {
                    // 蛇头
                    ctx.fillStyle = '#00ff00';
                    ctx.shadowColor = '#00ff00';
                    ctx.shadowBlur = 10;
                } else {
                    // 蛇身
                    ctx.fillStyle = '#00cc66';
                    ctx.shadowColor = '#00cc66';
                    ctx.shadowBlur = 5;
                }
                
                ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize - 1, gridSize - 1);
                ctx.shadowBlur = 0;
            });
            
            // 绘制食物
            ctx.fillStyle = '#ff0066';
            ctx.shadowColor = '#ff0066';
            ctx.shadowBlur = 10;
            ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize - 1, gridSize - 1);
            ctx.shadowBlur = 0;
        }

        // 移动蛇
        function moveSnake() {
            if (gamePaused || !gameRunning) return;
            
            // 在自动模式下计算下一步
            if (gameMode === 'auto') {
                calculateNextMove();
            }
            
            // 创建新蛇头
            const head = {x: snake[0].x + dx, y: snake[0].y + dy};
            
            // 检查碰撞边界
            if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
                gameOver();
                return;
            }
            
            // 检查碰撞自己
            for (let i = 0; i < snake.length; i++) {
                if (snake[i].x === head.x && snake[i].y === head.y) {
                    gameOver();
                    return;
                }
            }
            
            // 将新头添加到蛇数组开头
            snake.unshift(head);
            
            // 检查是否吃到食物
            if (head.x === food.x && head.y === food.y) {
                // 增加分数
                score += 10;
                scoreElement.textContent = score;
                
                // 创建粒子效果
                createParticles(food.x, food.y, '#ff0066', 15);
                
                // 每100分增加速度
                if (score % 100 === 0 && gameSpeed < 10) {
                    gameSpeed++;
                    speedElement.textContent = gameSpeed;
                    speedSlider.value = gameSpeed;
                }
                
                // 放置新食物
                placeFood();
            } else {
                // 移除蛇尾
                snake.pop();
            }
            
            // 重新绘制
            draw();
        }

        // 自动模式下的寻路算法
        function calculateNextMove() {
            // 简单的寻路算法：直接朝食物方向移动，并避免碰撞
            const head = snake[0];
            
            // 计算到食物的方向
            let newDx = 0;
            let newDy = 0;
            
            if (head.x < food.x) newDx = 1;
            else if (head.x > food.x) newDx = -1;
            else if (head.y < food.y) newDy = 1;
            else if (head.y > food.y) newDy = -1;
            
            // 避免直接反向移动
            if ((newDx !== 0 && newDx !== -dx) || (newDy !== 0 && newDy !== -dy)) {
                // 检查这个移动是否安全（不会撞到自己）
                const newHead = {x: head.x + newDx, y: head.y + newDy};
                let collision = false;
                
                // 检查是否会撞到自己
                for (let i = 0; i < snake.length; i++) {
                    if (snake[i].x === newHead.x && snake[i].y === newHead.y) {
                        collision = true;
                        break;
                    }
                }
                
                // 检查是否会撞到边界
                if (newHead.x < 0 || newHead.x >= tileCount || newHead.y < 0 || newHead.y >= tileCount) {
                    collision = true;
                }
                
                // 如果移动是安全的，则更新方向
                if (!collision) {
                    dx = newDx;
                    dy = newDy;
                    return;
                }
            }
            
            // 如果无法直接朝食物移动，则尝试其他安全方向
            const directions = [
                {dx: 0, dy: -1}, // 上
                {dx: 1, dy: 0},  // 右
                {dx: 0, dy: 1},  // 下
                {dx: -1, dy: 0}  // 左
            ];
            
            // 遍历所有可能的方向
            for (let dir of directions) {
                // 跳过反向移动
                if (dir.dx === -dx && dir.dy === -dy) continue;
                
                const newHead = {x: head.x + dir.dx, y: head.y + dir.dy};
                let collision = false;
                
                // 检查是否会撞到自己
                for (let i = 0; i < snake.length; i++) {
                    if (snake[i].x === newHead.x && snake[i].y === newHead.y) {
                        collision = true;
                        break;
                    }
                }
                
                // 检查是否会撞到边界
                if (newHead.x < 0 || newHead.x >= tileCount || newHead.y < 0 || newHead.y >= tileCount) {
                    collision = true;
                }
                
                // 如果找到安全方向，则更新方向并返回
                if (!collision) {
                    dx = dir.dx;
                    dy = dir.dy;
                    return;
                }
            }
            
            // 如果没有安全方向，保持当前方向（这可能导致游戏结束）
        }

        // 游戏结束
        function gameOver() {
            gameRunning = false;
            clearInterval(gameLoopInterval);
            
            // 创建游戏结束粒子效果
            const head = snake[0];
            createParticles(head.x, head.y, '#ff0000', 30);
            
            // 更新最高分
            if (score > highScore) {
                highScore = score;
                localStorage.setItem('snakeHighScore', highScore);
                highScoreElement.textContent = highScore;
            }
            
            // 显示游戏结束信息
            setTimeout(() => {
                alert(`游戏结束! 你的得分: ${score}`);
            }, 100);
        }

        // 开始游戏
        function startGame() {
            if (!gameRunning) {
                gameRunning = true;
                gamePaused = false;
                initGame();
                gameLoop();
            }
        }

        // 暂停/继续游戏
        function togglePause() {
            if (!gameRunning) return;
            
            gamePaused = !gamePaused;
            if (!gamePaused) {
                gameLoop();
            }
        }

        // 重新开始游戏
        function restartGame() {
            clearInterval(gameLoopInterval);
            gameRunning = false;
            gamePaused = false;
            initGame();
        }

        // 游戏主循环
        function gameLoop() {
            if (gameLoopInterval) clearInterval(gameLoopInterval);
            
            const speedInterval = 200 - (gameSpeed - 1) * 15; // 速度越快，间隔越短
            gameLoopInterval = setInterval(moveSnake, speedInterval);
        }

        // 键盘控制
        function handleKeyPress(e) {
            if (!gameRunning || gameMode !== 'manual' || gamePaused) return;
            
            switch(e.key) {
                case 'ArrowUp':
                    if (dy === 0) { // 避免反向移动
                        dx = 0;
                        dy = -1;
                    }
                    break;
                case 'ArrowDown':
                    if (dy === 0) {
                        dx = 0;
                        dy = 1;
                    }
                    break;
                case 'ArrowLeft':
                    if (dx === 0) {
                        dx = -1;
                        dy = 0;
                    }
                    break;
                case 'ArrowRight':
                    if (dx === 0) {
                        dx = 1;
                        dy = 0;
                    }
                    break;
                case ' ':
                    togglePause();
                    break;
            }
        }

        // 设置事件监听器
        startBtn.addEventListener('click', startGame);
        pauseBtn.addEventListener('click', togglePause);
        restartBtn.addEventListener('click', restartGame);
        
        speedSlider.addEventListener('input', function() {
            gameSpeed = parseInt(this.value);
            speedElement.textContent = gameSpeed;
            if (gameRunning) {
                gameLoop();
            }
        });
        
        manualModeBtn.addEventListener('click', function() {
            gameMode = 'manual';
            this.style.backgroundColor = '#00ffcc';
            this.style.color = '#121212';
            autoModeBtn.style.backgroundColor = '#1e1e1e';
            autoModeBtn.style.color = '#00ffcc';
        });
        
        autoModeBtn.addEventListener('click', function() {
            gameMode = 'auto';
            this.style.backgroundColor = '#00ffcc';
            this.style.color = '#121212';
            manualModeBtn.style.backgroundColor = '#1e1e1e';
            manualModeBtn.style.color = '#00ffcc';
        });
        
        document.addEventListener('keydown', handleKeyPress);
        
        // 窗口失去焦点时暂停游戏
        window.addEventListener('blur', function() {
            if (gameRunning && !gamePaused) {
                gamePaused = true;
            }
        });
        
        // 窗口获得焦点时恢复游戏
        window.addEventListener('focus', function() {
            if (gameRunning && gamePaused) {
                // 用户可以选择是否继续游戏
            }
        });
        
        // 初始化游戏
        initGame();
        highScoreElement.textContent = highScore;
        
        // 设置初始模式按钮状态
        manualModeBtn.style.backgroundColor = '#00ffcc';
        manualModeBtn.style.color = '#121212';
    </script>
</body>
</html>